package com.chuang.bootplus.controller.admin.listener.document;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.chuang.bootplus.entity.document.Document;
import com.chuang.bootplus.service.DocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
public class DocumentReadListener implements ReadListener<Document> {


    private static final int BATCH_COUNT = 100;
    private List<Document> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final DocumentService documentService;
    private final String time;

    public DocumentReadListener(DocumentService documentService,String time) {
        this.documentService=documentService;
        this.time=time;
        saveData();
        log.info("数据解析完成！");
    }


    private void saveData() {
        documentService.saveBatch(cachedDataList);
    }

    @Transactional
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        saveData();
        log.info("存储数据库成功！");
    }

    @Override
    public void invoke(Document document, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(document));
        document.setAddTime(time);
        cachedDataList.add(document);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

}
